import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { AppState, WindowState } from '@shared/types';
import { WINDOW_CONFIG } from '@shared/constants';

interface AppStore extends AppState {
  // 状态更新方法
  setSidebarCollapsed: (collapsed: boolean) => void;
  toggleSidebar: () => void;
  setCurrentPage: (page: string) => void;
  setWindowState: (state: Partial<WindowState>) => void;
  updateWindowBounds: (bounds: { width: number; height: number; x?: number; y?: number }) => void;
  setWindowMaximized: (maximized: boolean) => void;
  setWindowMinimized: (minimized: boolean) => void;

  // 初始化方法
  initApp: () => void;

  // 应用状态
  isMaximized: boolean;
  isMinimized: boolean;
  focused: boolean;
  setFocused: (focused: boolean) => void;
}

const defaultWindowState: WindowState = {
  width: WINDOW_CONFIG.defaultWidth,
  height: WINDOW_CONFIG.defaultHeight,
  maximized: false,
  minimized: false,
};

export const useAppStore = create<AppStore>()(
  persist(
    (set, get) => ({
      // 初始状态
      theme: 'light',
      sidebarCollapsed: false,
      currentPage: '/connections',
      windowState: defaultWindowState,
      isMaximized: false,
      isMinimized: false,
      focused: true,

      // 侧边栏控制
      setSidebarCollapsed: (collapsed: boolean) => {
        set({ sidebarCollapsed: collapsed });
      },

      toggleSidebar: () => {
        set((state) => ({ sidebarCollapsed: !state.sidebarCollapsed }));
      },

      // 页面导航
      setCurrentPage: (page: string) => {
        set({ currentPage: page });
        // 通知主进程页面变化
        if (window.electronAPI) {
          window.electronAPI.nav.navigate(page);
        }
      },

      // 窗口状态管理
      setWindowState: (state: Partial<WindowState>) => {
        set((prevState) => ({
          windowState: { ...prevState.windowState, ...state },
        }));
      },

      updateWindowBounds: (bounds) => {
        set((prevState) => ({
          windowState: {
            ...prevState.windowState,
            ...bounds,
          },
        }));
      },

      setWindowMaximized: (maximized: boolean) => {
        set({ isMaximized: maximized });
        set((prevState) => ({
          windowState: {
            ...prevState.windowState,
            maximized,
          },
        }));
      },

      setWindowMinimized: (minimized: boolean) => {
        set({ isMinimized: minimized });
        set((prevState) => ({
          windowState: {
            ...prevState.windowState,
            minimized,
          },
        }));
      },

      setFocused: (focused: boolean) => {
        set({ focused });
      },

      // 初始化应用
      initApp: async () => {
        try {
          // 获取应用信息
          if (window.electronAPI) {
            const version = await window.electronAPI.app.getVersion();
            const platform = await window.electronAPI.app.getPlatform();
            
            console.log(`App initialized - Version: ${version}, Platform: ${platform}`);

            // 获取窗口状态
            const windowState = await window.electronAPI.window.getState();
            if (windowState) {
              get().updateWindowBounds(windowState);
              get().setWindowMaximized(windowState.maximized);
              get().setWindowMinimized(windowState.minimized);
            }

            // 监听窗口事件
            setupWindowEventListeners();
          }
        } catch (error) {
          console.error('Failed to initialize app:', error);
        }
      },
    }),
    {
      name: 'app-storage',
      partialize: (state) => ({
        sidebarCollapsed: state.sidebarCollapsed,
        currentPage: state.currentPage,
        windowState: state.windowState,
      }),
    }
  )
);

// 设置窗口事件监听器
function setupWindowEventListeners() {
  if (!window.electronAPI) return;

  // 监听窗口最大化/还原
  window.electronAPI.window.onMaximized(() => {
    useAppStore.getState().setWindowMaximized(true);
  });

  window.electronAPI.window.onUnmaximized(() => {
    useAppStore.getState().setWindowMaximized(false);
  });

  // 监听窗口焦点变化
  window.electronAPI.window.onFocused(() => {
    useAppStore.getState().setFocused(true);
  });

  window.electronAPI.window.onBlurred(() => {
    useAppStore.getState().setFocused(false);
  });

  // 监听主题变化
  if (window.electronAPI.theme) {
    // 这里可以添加主题变化监听逻辑
  }
}

// 导出快捷操作函数
export const appActions = {
  navigateToPage: (page: string) => {
    useAppStore.getState().setCurrentPage(page);
  },
  
  toggleSidebar: () => {
    useAppStore.getState().toggleSidebar();
  },
  
  minimizeWindow: async () => {
    if (window.electronAPI) {
      await window.electronAPI.window.minimize();
    }
  },
  
  maximizeWindow: async () => {
    if (window.electronAPI) {
      await window.electronAPI.window.maximize();
    }
  },
  
  closeWindow: async () => {
    if (window.electronAPI) {
      await window.electronAPI.window.close();
    }
  },
};